package com.monkeyboy.manager.redis.redissharded;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * 分布式环境redissharded,分片访问
 * 
 *
 * @author Gavin<br>
 *         2020年6月3日
 */
@Configuration
public class RedisShardedPoolFactory {
	@Autowired
	private RedisShardedConfig redisShardedConfig;

	@Bean
	public ShardedJedisPool jedisShardFactory() {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		// 配置redis连接池的一些常用属性
		poolConfig.setMaxIdle(redisShardedConfig.getPoolMaxldle());
		poolConfig.setMaxTotal(redisShardedConfig.getPoolMaxTotal());
		poolConfig.setMinIdle(redisShardedConfig.getPoolMinIdle());
		poolConfig.setMaxWaitMillis(redisShardedConfig.getPoolMaxWait());
		poolConfig.setTestOnBorrow(redisShardedConfig.isPoolTestOnBorrow());
		poolConfig.setTestOnReturn(redisShardedConfig.isPoolTestOnReturn());
		poolConfig.setBlockWhenExhausted(redisShardedConfig.isPoolBlockWhenExhausted());

		JedisShardInfo info1 = new JedisShardInfo(redisShardedConfig.getHost1(), redisShardedConfig.getPort1(),
				1000 * 2);
		// info1.setPassword("设置连接密码");
		JedisShardInfo info2 = new JedisShardInfo(redisShardedConfig.getHost2(), redisShardedConfig.getPort2(),
				1000 * 2);
		List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
		jedisShardInfoList.add(info1);
		jedisShardInfoList.add(info2);
		//murmur_hash,分片策略
		ShardedJedisPool shardedJedisPool = new ShardedJedisPool(poolConfig, jedisShardInfoList, Hashing.MURMUR_HASH,Sharded.DEFAULT_KEY_TAG_PATTERN);
		return shardedJedisPool;
	}
}
